﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Reflection;
using System.Linq.Expressions;

namespace ProjetoComperio.SystemFramework.Extensions
{
    public static class IQueryableExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="ValueName"></param>
        /// <param name="textName"></param>
        /// <returns></returns>
        public static List<SelectListItem> ToSelectedItemList(this  IEnumerable source, String ValueName, String textName)
        {
            List<SelectListItem> selectedItens = new List<SelectListItem>();
            PropertyInfo valueProperty = null, textProperty = null;
            IEnumerator enumerator = source.GetEnumerator();
            //enumerator.Reset();
            while (enumerator.MoveNext())
            {
                valueProperty = enumerator.Current.GetType().GetProperty(ValueName);
                textProperty = enumerator.Current.GetType().GetProperty(textName);
                break;
            }

            foreach (var item in source)
                selectedItens.Add(new SelectListItem() { Selected = false, Value = valueProperty.GetValue(item, null).ToString(), Text = textProperty.GetValue(item, null).ToString() });


            return selectedItens;
        }
        public static List<SelectListItem> ToSelectedItemList<T>(this  IEnumerable<T> source, String propertyValueName, String propertyTextName) where T : class
        {
            List<SelectListItem> selectedItens = new List<SelectListItem>();

            if (source == null)
                return selectedItens;

            PropertyInfo valueProperty = typeof(T).GetProperty(propertyValueName);
            PropertyInfo textProperty = typeof(T).GetProperty(propertyTextName);

            foreach (var item in source)
                selectedItens.Add(new SelectListItem() { Selected = false, Value = valueProperty.GetValue(item, null).ToString(), Text = textProperty.GetValue(item, null).ToString() });

            return selectedItens;
        }
        public static List<SelectListItem> ToSelectedItemList<T>(this  IEnumerable<T> source, Expression<Func<T, object>> propertyValueName, Expression<Func<T, object>> propertyTextName) where T : class
        {

            return null;
        }


    }
}
